# Restoring the environment
renv::restore()

# Loading the replication package functions
source("AKMland_functions.R")

# Simulating data and running estimation functions on the simulated data
sim_panel <- mobsim()

d <- dataprep(sim_panel[[1]])
d[, firmsize := uniqueN(indiv_id), by=firm_id]
d[, c("age_2","age_3") := list((AGE-40)^2,(AGE-40)^3)]

akm_estim <- all_est(d, method="Card")
split_estim <- split_est(d, method = "yearly mean", split_type = "by_firm_movers")

sim_estim <- rotestim(built_panel=d, )

# Formatting simulated data as yearly files
sim_data <- mobsim(nworkers=10000, 
                   nfirms=1000, 
                   mobility=0.6,    # share of mobile workers in panel
                   nyears=18,        # length of panel in years
                   startyear=2002,
                   r=0.5,           # parameter for correlation between worker and firm fixed effects
                   var_wfe=0.15,    # Parameter for variance of WFE
                   var_ffe=0.01,    # Parameter for variance of FFE
                   var_u=0.01,      # Parameter for variance of u
                   var_yfe=0,       # Parameter for variance of year fixed effects
                   par_cor_u=0,     # Parameter for correlation u_t with u_t-1 for non-movers
                   par_age=0.004,    # Parameter for variable AGE in equation
                   par_age2=-0.0004,  # Parameter for variable (AGE-40)^2 in equation
                   par_age3=0.000008,  # Parameter for variable (AGE-40)^2 in equation
                   ytrend = 0    # Parameter for trend in year effects
)

d <- sim_data[[1]]
d <- d[, c("wfe","ffe","yfe","u"):=NULL]  # remove simulated latent variables
d$ident <- as.character(d$ident)
d$firm <- as.character(d$firm)

for (y in 2002:2019){
  write_sas(d[year==y,], paste(sasrep, "salarp", y, ".sas7bdat", sep = ""))
}

for (year in 2002:2019){
  fst_translate(year)
}


rotestim(built_panel=NULL, 
         period_length=6, 
         start_year_list=c(2002, 2008, 2014), 
         saverep = saverepdt,
         method_list=c("AKM","fsplit","psplit"), 
         estab=FALSE, 
         cluster=FALSE,
         rotat_year=FALSE, 
         year_method="yearlymean", 
         statdes=FALSE, 
         saveopt=TRUE,
         agemin=16, 
         agemax=70, 
         dureemin=360, 
         sizemin=1, 
         assoc=TRUE, 
         return_panel=FALSE, 
         save_estim=FALSE, 
         savenametag="")

